﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using MixScriptWeb.Share;
using MixScript.BLL;
using MixScriptWeb.control;
using MixScript.BLL.FI;
using MixScript.BLL.Accounting;
using System.Xml;
using System.Globalization;

namespace MixScriptWeb.Accounting
{
    public partial class fAccJournal : cCommonWeb, IMIxCommon // System.Web.UI.Page
    {
        private ListGeneralJournal journals;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                journals = new ListGeneralJournal();
                Session["journal"] = journals;
                LoadData((string)Request.QueryString["editID"]);
                txtDetAmm.Attributes.Add("onKeyUp", "javascript:GetConvert();");
                txtDetRate.Attributes.Add("onKeyUp", "javascript:GetConvert();");
                ddlDetailDC_selectedChange(null, null);

            }
        }
        private void LoadData(string editID)
        {

            txtDate.Text = String.Format("{0:dd-MM-yyyy}", DateTime.Now);
            if (Request.QueryString["type"] == "4")
            {
                Page.Title = "Account Receivable";
                lblTitle.Text = "Account Receivable";
                txtFirstNo.Text = "BR" + txtDate.Text.Split('-')[1];
                lblDC.Text = "Debit";
                ddlDetailDC.SelectedIndex = 1;
            }
            else
            {
                Page.Title = "Account Payable";
                lblTitle.Text = "Account Payable";
                txtFirstNo.Text = "BP" + txtDate.Text.Split('-')[1];
                lblDC.Text = "Credit";
                ddlDetailDC.SelectedIndex = 0;
            }
            cAccHeader gj = new cAccHeader();
            txtSecondNo.Text = gj.getMaxJournalNo(txtFirstNo.Text, DateTime.Now.Year);

            GlobalFunction funct = new GlobalFunction();
            DataTable dt = new DataTable();
            dt = funct.InizializeColumn();
            if (dt.Rows.Count > 0)
            {
                gvdetail.DataSource = dt;
                gvdetail.DataBind();
            }
            else
            {

                funct.ShowNoResultFound(dt, gvdetail);
            }

            FillDropDownList(ddlCurrency, "mst_currency", "currency", "currency", true);
            FillDropDownList(ddlDetailCurrency, "mst_currency", "currency", "currency", true);
            FillDropDownList(ddlCashCurrency, "mst_currency", "currency", "currency", true);

            cReferences oref = new cReferences();
            if (oref.getComboboxdata("accaccounts", "acctnum +'-'+ acctname  acctname", "acctnum", "", ref dt))
            {
                ddlDetailAccountNo.DataTextField = "acctname";
                ddlDetailAccountNo.DataValueField = "acctnum";
                ddlDetailAccountNo.DataSource = dt;
                ddlDetailAccountNo.DataBind();
            }
            if (editID != null)
            {

                cAccHeader gaj = new cAccHeader();
                Session["journal"] = gaj.loadJournalsub(editID);
                journals = (ListGeneralJournal)Session["journal"];
                gvdetail.DataSource = journals.ListOfJournal;
                gvdetail.DataBind();

            }
            dt = new DataTable();
            cAccHeader acc = new cAccHeader();
            String type;
            if (Request.QueryString["type"] == "4")
                type = "4";
            else
                type = "7";
            acc.getAccByProcess(out dt, type);
            ddlCashAccount.DataSource = dt;
            ddlCashAccount.DataTextField = "acctname";
            ddlCashAccount.DataValueField = "acctnum";
            ddlCashAccount.DataBind();

            ddlCashCurrency_indexChange(null, null);
            ddlDetailCurrency_indexChange(null, null);

        }


        public bool isvalid()
        {
            if (txtDescription.Text == string.Empty)
            {
                //mn = (MainMenu)this.Master;
                ShowStatusBar("Header description cannot be empty");
                return false;
            }
            return true;
        }

        protected void gvdetail_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Int32 debit, credit, total;
                Int32.TryParse(e.Row.Cells[7].Text, out debit);
                Int32.TryParse(e.Row.Cells[8].Text, out credit);
                total = debit - credit;
                txtSumDebet.Text = Convert.ToString(debit);
                txtSumKredit.Text = Convert.ToString(credit);
                txtSumTotal.Text = Convert.ToString(total);
            }
        }
        protected void ddlCashCurrency_indexChange(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            cCurrency cur = new cCurrency();

            cur.GetCurrency(out dt, txtDate.Text.Split('-')[2], txtDate.Text.Split('-')[1], ddlCashCurrency.SelectedItem.Value);
            if (dt.Rows.Count == 0)
                txtDetRate.Text = "1";
            else
            {  //rate , jual , beli
                if (ddlCashKurs.SelectedIndex == 0)
                    txtCashRate.Text = dt.Rows[0].ItemArray[2].ToString();
                else if (ddlCashKurs.SelectedIndex == 1)
                    txtCashRate.Text = dt.Rows[0].ItemArray[3].ToString();
                else if (ddlCashKurs.SelectedIndex == 2)
                    txtCashRate.Text = dt.Rows[0].ItemArray[4].ToString();
                else
                    txtCashRate.Text = "1";
            }

        }
        protected void ddlDetailCurrency_indexChange(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            cCurrency cur = new cCurrency();

            cur.GetCurrency(out dt, txtDate.Text.Split('-')[2], txtDate.Text.Split('-')[1], ddlDetailCurrency.SelectedItem.Value);
            if (dt.Rows.Count == 0)
                txtDetRate.Text = "1";
            else
            {  //rate , jual , beli
                if (ddlDetailKurs.SelectedIndex == 0)
                {
                    txtDetRate.Text = dt.Rows[0].ItemArray[2].ToString().Split('.')[0].ToString();
                    hfDetRate.Value = dt.Rows[0].ItemArray[2].ToString().Split('.')[0].ToString();
                }
                else if (ddlDetailKurs.SelectedIndex == 1)
                {
                    txtDetRate.Text = dt.Rows[0].ItemArray[3].ToString().Split('.')[0].ToString();
                    hfDetRate.Value = dt.Rows[0].ItemArray[3].ToString().Split('.')[0].ToString();
                }
                else if (ddlDetailKurs.SelectedIndex == 2)
                {
                    txtDetRate.Text = dt.Rows[0].ItemArray[4].ToString().Split('.')[0].ToString();
                    hfDetRate.Value = dt.Rows[0].ItemArray[4].ToString().Split('.')[0].ToString();
                }
                else
                    txtDetRate.Text = "1";
            }

        }
        protected void gvdetail_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Updated")
            {
                GeneralJournal journal = new GeneralJournal();
                journals = (ListGeneralJournal)Session["journal"];

                ViewState["ID"] = Convert.ToInt32(e.CommandArgument);
                journal = journals.GetJournal(Convert.ToInt32(e.CommandArgument));
                txtDetAmm.Text = journal.ammount.ToString();


                ddlDetailAccountNo.SelectedItem.Value = journal.acct.ToString();
                ddlDetailAccountNo_indexChange(null, null);


                txtDetailDescription.Text = journal.description;
                ddlDetailCurrency.SelectedItem.Value = journal.currency;
                Int32 rate;
                Int32.TryParse(ddlDetailKurs.SelectedValue, out rate);
                if (journal.debit == 0)
                {
                    txtDetAmm.Text = journal.credit.ToString();
                }
                else
                {
                    txtDetAmm.Text = journal.debit.ToString();
                }
                txtDetRate.Text = journal.rate.ToString();
                if (journal.subsidiary != "")
                    ddlSubsidiaryNo.SelectedItem.Value = journal.subsidiary;

                txtDetailInvoice.Text = journal.invoice.ToString();
                txtDetailDate.Text = String.Format("{0:DD-MM-yyyy}", journal.invoiceDate.ToString());
                txtDetailTerms.Text = journal.terms.ToString();
            }
            else if (e.CommandName == "Deleted")
            {
                GeneralJournal journal = new GeneralJournal();
                journals = (ListGeneralJournal)Session["journal"];
                Session["journal"] = journals.DeleteJournal(Convert.ToInt32(e.CommandArgument));
                journals = (ListGeneralJournal)Session["journal"];
                gvdetail.DataSource = journals.ListOfJournal;
                gvdetail.DataBind();

            }

        }
        protected void ddlDetailDC_selectedChange(Object sender, EventArgs e)
        {
            try
            {
                cReferences oref = new cReferences();
                cAccSubLedger gj = new cAccSubLedger();
                DataTable dt = new DataTable();
                pnlInvoiceSel.Style["display"] = "none";
                pnlInvoiceText.Style["display"] = "block";
                dt = new DataTable();
                ddlInvoice.Items.Clear();
                String subID = "";
                if (ddlSubsidiaryNo.SelectedItem != null)
                    subID = ddlSubsidiaryNo.SelectedItem.Value.ToString();
                else
                    return;
                if (gj.getAcc(out dt, (string)ddlDetailAccountNo.SelectedItem.Value))
                {
                    if (dt.Rows[0].ItemArray[7].ToString() == "4")
                    {
                        if (ddlDetailDC.SelectedItem.Value == "C")
                        {
                            pnlInvoiceSel.Style["display"] = "block";
                            pnlInvoiceText.Style["display"] = "none";
                            if (oref.getComboboxdata(" tb_dnmst mst inner join tb_invdtl det On  mst.delno=det.delno ", "invno", "invno", "cuid='" + subID + "'", ref dt))
                            {
                                ddlInvoice.DataTextField = "invno";
                                ddlInvoice.DataValueField = "invno";
                                ddlInvoice.DataSource = dt;
                                ddlInvoice.DataBind();
                            }
                        }

                    }
                    else if (dt.Rows[0].ItemArray[7].ToString() == "7")
                    {
                        if (ddlDetailDC.SelectedItem.Value == "C")
                        {
                            pnlInvoiceSel.Style["display"] = "block";
                            pnlInvoiceText.Style["display"] = "none";
                            if (oref.getComboboxdata("tb_pomst", "pono", "pono", "codfbpid='" + subID + "'", ref dt))
                            {
                                ddlInvoice.DataTextField = "pono";
                                ddlInvoice.DataValueField = "pono";
                                ddlInvoice.DataSource = dt;
                                ddlInvoice.DataBind();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            { }
        }
        protected void ddlDetailAccountNo_indexChange(object sender, EventArgs e)
        {

            DataTable dt = new DataTable();
            cAccSubLedger gj = new cAccSubLedger();
            if (gj.getSubsidiary(ref dt, (string)ddlDetailAccountNo.SelectedItem.Value)) ;
            {

                if (dt.Rows.Count > 0)
                {

                    ddlSubsidiaryNo.DataTextField = "name";
                    ddlSubsidiaryNo.DataValueField = "no";
                    ddlSubsidiaryNo.Enabled = true;
                    ddlSubsidiaryNo.DataSource = dt;
                    ddlSubsidiaryNo.DataBind();
                }
                else
                {
                    ddlSubsidiaryNo.Items.Clear();
                    ddlSubsidiaryNo.DataSource = null;
                    ddlSubsidiaryNo.DataBind();
                    ddlSubsidiaryNo.Enabled = false;

                }
            }
            String subID = "";
            if (ddlSubsidiaryNo.SelectedItem != null)
                subID = ddlSubsidiaryNo.SelectedItem.Value.ToString();
            pnlInvoiceSel.Style["display"] = "none";
            pnlInvoiceText.Style["display"] = "block";
            dt = new DataTable();
            cReferences oref = new cReferences();
            ddlInvoice.Items.Clear();
            if (gj.getAcc(out dt, (string)ddlDetailAccountNo.SelectedItem.Value))
            {
                if (dt.Rows[0].ItemArray[7].ToString() == "4")
                {
                    if (ddlDetailDC.SelectedItem.Value == "C")
                    {
                        pnlInvoiceSel.Style["display"] = "block";
                        pnlInvoiceText.Style["display"] = "none";
                        if (oref.getComboboxdata(" tb_dnmst mst inner join tb_invdtl det On  mst.delno=det.delno ", "invno", "invno", "cuid='" + subID + "'", ref dt))
                        {
                            ddlInvoice.DataTextField = "invno";
                            ddlInvoice.DataValueField = "invno";
                            ddlInvoice.DataSource = dt;
                            ddlInvoice.DataBind();
                        }
                    }

                }
                else if (dt.Rows[0].ItemArray[7].ToString() == "7")
                {
                    if (ddlDetailDC.SelectedItem.Value == "C")
                    {
                        pnlInvoiceSel.Style["display"] = "block";
                        pnlInvoiceText.Style["display"] = "none";
                        if (oref.getComboboxdata("tb_pomst", "pono", "pono", "codfbpid='" + subID + "'", ref dt))
                        {
                            ddlInvoice.DataTextField = "pono";
                            ddlInvoice.DataValueField = "pono";
                            ddlInvoice.DataSource = dt;
                            ddlInvoice.DataBind();
                        }
                    }
                }
            }

        }
        protected void btnSave_click(object sender, EventArgs e)
        {
            try
            {
                GeneralJournal journal = new GeneralJournal();
                journals = (ListGeneralJournal)Session["journal"];
                Int32 accNo;
                Int32.TryParse(ddlDetailAccountNo.SelectedValue, out accNo);
                journal.acct = accNo;
                Int32 ammount;
                Int32.TryParse(txtDetAmm.Text, out ammount);
                journal.ammount = ammount;

                Int32 convrt;
                Int32.TryParse(hfDetConvert.Value, out convrt);

                if (journals.ListOfJournal == null)
                {
                    journals.ListOfJournal = new List<GeneralJournal>();
                    journal.id = 1;
                    journal.no = 1;
                }
                else
                {
                    journal.id = journals.ListOfJournal.Count + 1;
                    journal.no = journal.id;
                }

                journal.description = txtDetailDescription.Text;
                journal.currency = ddlDetailCurrency.SelectedValue;

                journal.rate = Convert.ToInt32(hfDetRate.Value);

                if (ddlDetailDC.SelectedValue == "D")
                {
                    journal.debit = convrt;
                    journal.credit = 0;
                }
                else
                {
                    journal.credit = convrt;
                    journal.debit = 0;
                }
                journal.subsidiary = ddlSubsidiaryNo.SelectedValue;
                Int32 invoice;
                Int32.TryParse(txtDetailInvoice.Text, out invoice);
                journal.invoice = invoice;

                String sDate = txtDetailDate.Text;
                if (sDate == "" || sDate == string.Empty)
                    journal.invoiceDate = DateTime.MinValue;
                else
                    journal.invoiceDate = Convert.ToDateTime(txtDetailDate.Text, new CultureInfo("ru-RU"));
                journal.terms = txtDetailTerms.Text;
                journal.kurs = ddlDetailKurs.SelectedItem.Value;

                if (ViewState["ID"] == null)
                    journals.ListOfJournal.Add(journal);
                else
                    journals = journals.UpdateJournal(Convert.ToInt32(ViewState["ID"]), journal);



                Int32 poInvoice;
                Int32.TryParse(txtPoInvice.Text, out poInvoice);
                journal.poInvoice = poInvoice;
                String sDate1 = txtPoInvoiceDate.Text;
                if (sDate1 == "" || sDate1 == string.Empty)
                    journal.poInvoiceDate = DateTime.MinValue;
                else
                    journal.poInvoiceDate = Convert.ToDateTime(txtPoInvoiceDate.Text, new CultureInfo("ru-RU"));
                txtCashCredit.Text = Convert.ToString(journals.GetTotal()).Replace("-", "");
                txtCashConvert.Text = Convert.ToString(journals.GetTotal()).Replace("-", "");
                txtSumDebet.Text = Convert.ToString(journals.GetDebit()).Replace("-", "");
                txtSumKredit.Text = Convert.ToString(journals.GetCredit()).Replace("-", "");
                if (txtFirstNo.Text.ToLower().Contains('r'))
                    txtSumDebet.Text = Convert.ToString(Convert.ToInt32(txtCashCredit.Text)).Replace("-", "");
                else
                    txtSumKredit.Text = Convert.ToString(Convert.ToInt32(txtCashCredit.Text)).Replace("-", "");
                txtSumTotal.Text = (Convert.ToInt32(txtSumDebet.Text) - Convert.ToInt32(txtSumKredit.Text)).ToString();


                gvdetail.DataSource = journals.ListOfJournal;
                gvdetail.DataBind();

                Session["journal"] = journals;
                ViewState["ID"] = null;
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message);
            }
            clear(false);
        }
        private void clear(bool All)
        {

            if (All)
            {
                Session["journal"] = null;
                journals = new ListGeneralJournal();
                txtFirstNo.Text = string.Empty;
                txtSecondNo.Text = string.Empty;
                txtSecondNo.Text = string.Empty;
                txtDescription.Text = string.Empty;
            }
            ddlDetailAccountNo.SelectedIndex = 0;
            ddlSubsidiaryNo.Items.Clear();
            txtDetAmm.Text = string.Empty;
            txtDetConvert.Text = string.Empty;
            txtDetailDate.Text = string.Empty;
            txtDetailDescription.Text = string.Empty;
            txtDetailInvoice.Text = string.Empty;
            txtDetailTerms.Text = string.Empty;


        }
        protected void btnSaveAll_click(object sender, EventArgs e)
        {
            if (isvalid())
            {
                ListGeneralJournal journals = new ListGeneralJournal();
                journals = (ListGeneralJournal)Session["journal"];
                cAccHeader gj = new cAccHeader();
                if ((string)Request.QueryString["editID"] != null)
                {
                    gj.updateJournal((string)Request.QueryString["editID"], txtFirstNo.Text, txtSecondNo.Text, ddlCurrency.SelectedItem.Value,
                    txtDescription.Text, DateTime.Parse(txtDate.Text, new CultureInfo("ru-RU")), journals,
                           ddlCashAccount.SelectedItem.Value, ddlCashCurrency.SelectedItem.Value, ddlCashKurs.SelectedItem.Value, txtCashDescripiton.Text, txtCashRate.Text, txtCashCredit.Text, txtCashConvert.Text, null);
                }
                else
                {
                    gj.saveJournal(txtFirstNo.Text, txtSecondNo.Text, ddlCurrency.SelectedItem.Value,
                        txtDescription.Text, DateTime.Parse(txtDate.Text, new CultureInfo("ru-RU")), journals,
                        ddlCashAccount.SelectedItem.Value, ddlCashCurrency.SelectedItem.Value, ddlCashKurs.SelectedItem.Value, txtCashDescripiton.Text, txtCashRate.Text, txtCashCredit.Text, txtCashConvert.Text, null);
                }

                clear(true);
                //mn = (MainMenu)this.Master;
                Response.Redirect("ListJournal.aspx?type=" + (String)Request.QueryString["type"]);
            }
        }
        protected void btnReset_click(object sender, EventArgs e)
        {
            clear(true);
        }
    }
}